new Vue({
    el: '#app',
    data() {
        return {
            form: {
                value: '',
                PageNumber: 1,
                RowAmount: 20,
            },
            list: [],
            total: 0,
            // 合同确认弹窗与上下文
            dialogContractVisible: false,
            currentContractRow: null,
            pageSupply: null,
            currentSupplyId: '',
            stagedPayments: [],
            // 权限相关：当前企业与来源
            enterpriseId: '',
            fromApplyDetail: false,
        }
    },
    mounted() {
        this.getList();
    },
    methods: {
        handleBack() {
            window.location.href = './index.html';
        },
        handleSerach() {
            this.form.PageNumber = 1;
            this.getList();
        },
        // 状态文本映射：0-待审核，2-通过，3-拒绝
        formatStatus(status) {
            switch (String(status)) {
                case '0': return '待审核';
                case '2': return '通过';
                case '3': return '拒绝';
                default: return '未知';
            }
        },
        // 状态样式映射
        statusTagType(status) {
            switch (String(status)) {
                case '0': return 'warning';
                case '2': return 'success';
                case '3': return 'danger';
                default: return 'info';
            }
        },
        handlePageChange(page) {
            this.form.PageNumber = page;
            this.getList();
        },
        getList() {
            const enterpriseId = $.cookie('enterprise') || '';
            const keyword = this.form.value || '';
            const supplyId = (function () {
                try { return getQueryObject(window.location.href, 'supplyId') || ''; } catch (e) { return ''; }
            })();
            // 购买记录页职责：按 supplyId 展示其全部订单，忽略 applyId
            // 记录当前 SupplyId 以便顶部展示原信息
            this.currentSupplyId = supplyId;
            // 记录当前企业
            this.enterpriseId = enterpriseId;

            // 支持：按当前企业或指定报价编号过滤（状态：0待接受、2已接受、3已拒绝）
            let condition = `Row_Status IN ('0','2','3')`;
            if (supplyId) {
                // 按报价编号筛选
                condition += ` AND Supply_Unit_Price_SerialNumber='${supplyId}'`;
            } else {
                // 默认：当前企业名下的有效报价单关联的订单
                condition += ` AND Supply_Unit_Price_SerialNumber IN (
                    SELECT Supply_Unit_Price_SerialNumber FROM supply_unitprice
                    WHERE Row_Status='0' AND Enterprise_Info_SerialNumber='${enterpriseId}'
                )`;
            }
            if (keyword) {
                const kw = String(keyword).replace(/'/g, "''");
                condition += ` AND (Supply_Order_SerialNumber LIKE '%${kw}%' OR Enterprise_Info_SerialNumber LIKE '%${kw}%')`;
            }

            httpRequest({
                url: '/generalBusiness/generalQueryByTableName',
                data: {
                    Data: 'supply_order',
                    Condition: condition,
                    PageNumber: this.form.PageNumber,
                    RowAmount: this.form.RowAmount,
                },
                type: 'GET'
            }).then(async res => {
                // res 可能是数组或分页对象，兼容处理
                if (Array.isArray(res)) {
                    this.list = res;
                    this.total = res.length;
                } else {
                    this.list = res.Data || [];
                    this.total = Number(res.Total || 0);
                }

                // 批量查询拒绝记录（supply_order_examine_log）并挂载到每条订单
                const ids = (this.list || []).map(i => i.Supply_Order_SerialNumber).filter(Boolean);
                if (ids.length > 0) {
                    try {
                        const logs = await httpRequest({
                            url: '/generalBusiness/generalQueryByTableName',
                            data: {
                                Data: 'supply_order_examine_log',
                                Condition: `Supply_Order_SerialNumber IN (${ids.map(id => `'${id}'`).join(',')})`
                            },
                            type: 'GET'
                        });
                        const arr = Array.isArray(logs) ? logs : (logs.Data || []);
                        const map = {};
                        arr.forEach(l => {
                            const k = l.Supply_Order_SerialNumber;
                            if (!map[k]) map[k] = [];
                            map[k].push(l);
                        });
                        this.list = this.list.map(row => ({
                            ...row,
                            examineLogs: map[row.Supply_Order_SerialNumber] || []
                        }));
                    } catch (e) {
                        // 查询日志失败不影响主列表
                    }
                }

                // 批量查询供应单原信息（supply_unitprice），并挂载到订单上方展示
                const supplyIds = [...new Set((this.list || []).map(i => i.Supply_Unit_Price_SerialNumber).filter(Boolean))];
                if (supplyIds.length > 0) {
                    try {
                        const supRes = await httpRequest({
                            url: '/generalBusiness/generalQueryByTableName',
                            data: {
                                Data: 'supply_unitprice',  //换成y_supply_unitprice sql标识：供应单原信息
                                Condition: `Supply_Unit_Price_SerialNumber IN (${supplyIds.map(id => `'${id}'`).join(',')})`
                            },
                            type: 'GET'
                        });
                        const supArr = Array.isArray(supRes) ? supRes : (supRes.Data || []);
                        const supMap = {};
                        supArr.forEach(s => { supMap[s.Supply_Unit_Price_SerialNumber] = s; });
                        this.list = this.list.map(row => ({
                            ...row,
                            originSupply: supMap[row.Supply_Unit_Price_SerialNumber] || null
                        }));
                        const firstSupplyId = (this.list[0] && this.list[0].Supply_Unit_Price_SerialNumber) || '';
                        this.pageSupply = supMap[this.currentSupplyId] || supMap[firstSupplyId] || null;

                        // 页面级分阶段付款方案：按当前顶部供应报价编号查询并排序
                        try {
                            const idsForStage = Object.keys(supMap);
                            const stagedRes = idsForStage.length ? await httpRequest({
                                url: '/generalBusiness/generalQueryByTableNameWithOriginal',
                                data: {
                                    Data: 'supply_unitprice_staged_payment',
                                    Condition: `Supply_Unit_Price_SerialNumber IN (${idsForStage.map(id => `'${id}'`).join(',')})`
                                },
                                type: 'GET'
                            }).catch(() => []) : [];
                            const stagedArr = Array.isArray(stagedRes) ? stagedRes : (stagedRes.Data || []);
                            const orderMap = { '定金': 1, '发货': 2, '到货': 3, '尾款': 4 };
                            const currentId = (this.pageSupply && this.pageSupply.Supply_Unit_Price_SerialNumber) || '';
                            this.stagedPayments = (stagedArr || [])
                                .filter(sp => sp.Supply_Unit_Price_SerialNumber === currentId)
                                .slice()
                                .sort((a, b) => (orderMap[String(a.Stage_Name || '').trim()] || 99) - (orderMap[String(b.Stage_Name || '').trim()] || 99));
                        } catch (e) {
                            this.stagedPayments = [];
                        }
                    } catch (e) {
                        
                    }
                }
            }).catch(() => {
                this.$message.error('查询失败，请稍后再试');
            });
        },
        // 操作按钮可见性：购买记录页不提供操作按钮
        canOperate() { return false; },
        // 格式化拒绝记录文案
        formatRejectLog(log, idx) {
            const reason = (log && log.Reason) ? log.Reason : '';
            const time = (log && (log.Create_Date || log.Operation_Datetime)) ? `（${log.Create_Date || log.Operation_Datetime}）` : '';
            return `${idx + 1}. ${reason}${time}`;
        },
        // 格式化原供应单地址
        formatSupplyAddress(s) {
            if (!s) return '';
            const p = s.ProvinceNumber || '';
            const c = s.CityNumber || '';
            const d = s.CountyNumber || '';
            const a = s.Detailed_Address || '';
            return `${p}${c}${d}${a}`;
        },
        // 剩余量（兼容无该字段的情况）
        getRemainQuantity(s) {
            if (!s) return '';
            if (s.Remain_Quantity !== undefined && s.Remain_Quantity !== null) return s.Remain_Quantity;
            const t = Number(s.Total_Quantity || 0);
            const sold = Number(s.Sales_Quantity || 0);
            return t - sold;
        },
        // 打开确认合同选择弹窗
        openContractDialog(row) {
            this.currentContractRow = row || null;
            this.dialogContractVisible = true;
        },
    }
});